<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>javascript grammar tree visualizer</title>
<style>
.symbolName {
    display:block;
}
.childContainer {
    padding-left:30px;
}
</style>
<script src="../source/LexicalParser.js"></script>
<script src="../source/SyntacticalParser.js"></script>
<script src="../source/Parser.js"></script>
<script>

var special = {
    "Program":visualizeRoot,
    "SourceElements":visualizeList,
    "ElementList":visualizeList,
    "PropertyNameAndValueList":visualizeList,
    "ArgumentList":visualizeList,
    "StatementList":visualizeList,
    "VariableDeclarationListNoIn":visualizeList,
    "VariableDeclarationList":visualizeList,
    "FormalParameterList":visualizeList
}

function visualizeList(container,node) {
    var i = node.childNodes.length;    
    while(i--)visualize(container,node.childNodes[i]);            
}
function visualizeRoot(container,node) {
    var title = document.createElement("span");
    title.className = "symbolName";
    title.innerText = node.name + (node.token!=undefined && node.name!=node.token?":"+node.token:"")
    container.appendChild(title);
    var div = document.createElement("div");
    div.className = "childContainer";
    var i = node.childNodes.length;
    container.appendChild(div);
    while(i--)visualize(div,node.childNodes[i]);
}

function visualize(container,node) {
    if(special[node.name]) return special[node.name](container,node);

    if(node.childNodes.length == 1 && !node.token) 
        return visualize(container,node.childNodes[0]); 

    var title = document.createElement("span");
    title.className = "symbolName";
    title.innerText = node.name + (node.token!=undefined && node.name!=node.token?":"+node.token:"")
    container.appendChild(title);
    var div = document.createElement("div");
    div.className = "childContainer";
    var i = node.childNodes.length;
    container.appendChild(div);
    while(i--)visualize(div,node.childNodes[i]);
}

window.onload = function(){
    
    document.querySelector("button").onclick = function(){
        try {
            var parser = new Parser();
            visualizer.innerHTML = "";
            var tree = parser.parse(document.querySelector("#code").value);
            visualize(document.querySelector("#visualizer"),tree);
        } catch(e) {
            visualizer.innerHTML = "<span style=\"color:red;\">"+e+"</span>"
        }
    }
}
</script>
</head>
<body>
<textarea id="code" style="width:100%;height:500px;"></textarea>
<button >parse</button>
    <div id="visualizer">

    </div>
    
</body>
</html>